package com.example.ywj.toutiao;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.example.ywj.toutiao.bean.Title;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.MyGridViewAdapter;
import com.example.ywj.toutiao.utils.MyGridViewAdapter2;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.example.ywj.toutiao.utils.SpUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class AddTitleActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "AddTitleActivity";
    private String baseUrl = Constant.BASEURL;
    @BindView(R.id.addTitle_gridView1)
    public GridView addTitle_gridView1;
    @BindView(R.id.addTitle_gridView2)
    public GridView addTitle_gridView2;
    @BindView(R.id.addTitle_back)
    public TextView addTitle_back;
    public List<Title> titleList = new ArrayList<>();
    public List<Title> titleLists = new ArrayList<>();
    public MyGridViewAdapter myGridViewAdapter;
    public MyGridViewAdapter2 myGridViewAdapter2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_title);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//因为不是所有的系统都可以设置颜色的，在4.4以下就不可以。。有的说4.1，所以在设置的时候要检查一下系统版本是否是4.1以上
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.colorAccent));
        }
        initView();
        getData2();
        Log.i(TAG, "onCreate: "+titleList.size());

    }
    public void initView(){
        Typeface font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        addTitle_back.setTypeface(font);
        addTitle_back.setText(getResources().getString(R.string.cha));
        addTitle_back.setOnClickListener(this);

    }
    private void getData2(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getData();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    JsonArray data = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    titleList = gson.fromJson(data,new TypeToken<ArrayList<Title>>(){}.getType());
                    myGridViewAdapter = new MyGridViewAdapter(titleList);
                    addTitle_gridView1.setAdapter(myGridViewAdapter);
                    getData3();
                    //setGridViewHeightByChildren(addTitle_gridView1);
                }else {
                    Log.i(TAG, "onResponse: 出错了");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    private void getData3(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getDatas();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    JsonArray data = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    titleLists = gson.fromJson(data,new TypeToken<ArrayList<Title>>(){}.getType());
                    myGridViewAdapter2 = new MyGridViewAdapter2(titleLists);
                    addTitle_gridView2.setAdapter(myGridViewAdapter2);
                    //setGridViewHeightByChildren(addTitle_gridView2);
                    addTitle_gridView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            //Log.i(TAG, "onItemClick: "+position);
                            Title title = titleLists.get(position);
                            if(!titleList.contains(title)){
                                titleList.add(title);
                                myGridViewAdapter.notifyDataSetChanged();
                                titleLists.remove(title);
                                myGridViewAdapter2.notifyDataSetChanged();
                            }
                            saveTitle(title.get_id());
                        }
                    });
                }else {
                    Log.i(TAG, "onResponse: 出错了");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    public void saveTitle(String id){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.saveTitle(id);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    Toasty.success(AddTitleActivity.this,"添加成功",Toasty.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: "+"请求失败");
            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.addTitle_back:
                SpUtils.putBoolean(AddTitleActivity.this,"isreturn",false);
                Intent intent = new Intent(AddTitleActivity.this,MainActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(0,R.anim.translate_dialog_out);
                break;
        }
    }

}
